import {
  selectCuesTopicManage,
  selectTopicManageTreeAssignOrganization,
  selectTopicManageTreeLinkageOrganization,
} from '@/services/api/api-cues-topic';
import {
  CloseCircleOutlined,
  FileTextOutlined,
  LikeOutlined,
  StopOutlined,
} from '@ant-design/icons';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { useAccess } from 'umi';
import { Avatar, Card, Cascader, Descriptions, Divider, Space, Tag, Typography } from 'antd';
import moment from 'moment';
import React, { useRef, useState } from 'react';
import TableSubmit from './TableTopicSubmit';

interface TableTopicAssistDetailsProps {
  item: CuesTopicData.TopicPage;
  onRefurbish: () => void;
}

const TableTopicAssistDetails: React.FC<TableTopicAssistDetailsProps> = ({ item, onRefurbish }) => {
  const access = useAccess();

  const formRef = useRef<ProFormInstance>();

  const [loading, setLoading] = useState(false);

  /**
   * 指派单位数据
   */
  const [treeAssignOrganizationData, setTreeAssignOrganizationDataState] = useState();

  /**
   * 联动单位数据
   */
  const [treeLinkageOrganizationData, setTreeLinkageOrganizationDataState] = useState();

  /**
   * 选题计划详情
   */
  const [dataTopicDetails, setDataTopicDetailsState] = useState<CuesTopicData.TopicSelectManage>();

  /**
   * 申请记录
   */

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          disabled: val.isFolder === 1  && val.isOrganization === 0 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载 保存 推送 单位
   */
  const loadSelectTopicManageTreeAssignOrganization = async () => {
    try {
      const response = await selectTopicManageTreeAssignOrganization({ id: item.id });
      if (response.code === 0) {
        setTreeAssignOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) {}
  };

  /**
   * 加载 保存 联动 单位
   */
  const loadSelectTopicManageTreeLinkageOrganization = async () => {
    try {
      const response = await selectTopicManageTreeLinkageOrganization({
        id: item.id,
      });
      if (response.code === 0) {
        setTreeLinkageOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) {}
  };

  /**
   * 加载 选题计划详情
   * @param key
   */
  const loadCuesTopicDetails = async () => {
    setLoading(true);
    try {
      const response = await selectCuesTopicManage({ id: item.id });
      const { code, data } = response;
      if (code === 0) {
        setDataTopicDetailsState(data);

        formRef.current?.setFieldsValue({
          deadlineTime: [data.createdTime, data.deadlineTime],
          assignOrganizationIds: data.cascaderAssignOrganizations,
          linkageOrganizationIds: data.cascaderLinkageOrganizations,
        });

        setLoading(false);
      }
    } catch (error) {}
  };

  /**
   * 级联组件 搜索筛选
   * @param inputValue
   * @param path
   * @returns
   */
  const filter = (inputValue: string, path) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  const IconText = ({ icon, text }: { icon: any; text: string }) => (
    <span style={{color:'#1677FF'}}>
      {React.createElement(icon, { style: { marginInlineEnd: 8 } })}
      {text}
    </span>
  );

  const TitleText = ({ title, text }: { title: string; text: any }) => (
    <span style={{color:'#1677FF'}}>
      {title}：{text}
    </span>
  );

  const drawerFormView = () => {
    let cover = '';

    let gradeName = '';
    let gradeColor = '';

    if (item.grade === 1) {
      cover = 'https://wx4.sinaimg.cn/mw2000/0033ImPzly1hj076fx0z4j60p00p00w502.jpg';
      gradeName = '重大';
      gradeColor = '#f50';
    } else if (item.grade === 2) {
      cover = 'https://wx2.sinaimg.cn/mw2000/0033ImPzly1hj076fx3ilj60p00p0wi502.jpg';
      gradeName = '重要';
      gradeColor = '#ffd591';
    } else if (item.grade === 3) {
      cover = 'https://wx2.sinaimg.cn/mw2000/0033ImPzly1hj076fwx7zj60p00p0tc802.jpg';
      gradeName = '一般';
      gradeColor = '#2db7f5';
    }

    let linkageTypeName = '';

    if (item.linkageType === 1) {
      linkageTypeName = '协助媒体';
    } else if (item.linkageType === 2) {
      linkageTypeName = '联动部门';
    } else if (item.linkageType === 3) {
      linkageTypeName = '协助媒体、单位';
    } else {
      linkageTypeName = '暂无';
    }

    let recordActions: React.JSX.Element[] | React.ReactNode[] | undefined = [];

    if (item.recordState === 1) {
      recordActions = [
        <IconText icon={CloseCircleOutlined} text="废弃" key="list-vertical-star-o" />,
        <IconText icon={StopOutlined} text="撤销" key="list-vertical-star-o" />,
        <IconText icon={LikeOutlined} text="发布" key="list-vertical-like-o" />,
        <IconText icon={LikeOutlined} text="详情" key="list-vertical-like-o" />,
      ];
    } else if (item.recordState === 2) {
      recordActions = [
        <IconText icon={CloseCircleOutlined} text="废弃" key="list-vertical-star-o" />,
        <IconText icon={FileTextOutlined} text="详情" key="list-vertical-like-o" />,
      ];
    } else if (item.recordState === 3) {
      if (access.线索征集x配置x提供者) {
        recordActions = [
          <TitleText
            key={'title_text_count_submit_organization'}
            title="报送线索"
            text={item.countSubmit}
          />,
        ];
      } else {
        recordActions = [
          <TitleText
            key={'title_text_count_submit_organization'}
            title="报送单位"
            text={item.countSubmitOrganization}
          />,
          <TitleText key={'title_text_count_submit'} title="报送线索" text={item.countSubmit} />,
        ];
      }
    } else {
      recordActions = [<IconText icon={LikeOutlined} text="详情" key="list-vertical-like-o" />];
    }


    return (
      <DrawerForm
        key="add_topic_drawer_form"
        title={
          <>
            <Tag color={gradeColor}>{gradeName}</Tag>
            <Tag color={item.run === 1 ? 'green' : item.run === 2 ? 'red' : 'orange'}>
              {item.run === 1 ? '进行中' : item.run === 2 ? '已结束' : '已暂停'}
            </Tag>
            {item.isLinkage === 1 && <Tag color="orange">{linkageTypeName}</Tag>}
            {dataTopicDetails?.name}
          </>
        }
        drawerProps={{
          // maskClosable: false,
          destroyOnClose: true,
          width: '100%',
        }}
        loading={loading}
        formRef={formRef}
        trigger={
          <div
            style={{
              paddingLeft: 10,
              paddingRight: 10,
              paddingBottom: 10,
            }}
          >
            <Card
              bordered={false}
              hoverable
              style={{
               
                background: 'linear-gradient(#F5FBFF,#fff, #fff)',
              }}
              // cover={<img height={200} src={cover} />}
              actions={recordActions}
              bodyStyle={{
                borderTop: '0px solid #f0f0f0',
              }}
            >
              <Card.Meta
                avatar={
                  <Avatar
                    style={{
                      marginTop: '2px',
                    }}
                    size={'large'}
                    src={item.createdOrganizationAvatar}
                  />
                }
                title={
                  // <div>
                  //   <span>{item.createdOrganizationName}</span>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    {/* <span>{item.createdOrganizationName}</span> */}
                    <div
                      style={{
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        minWidth: 65,
                      }}
                    >
                      {item.createdOrganizationName}
                    </div>
                    <div
                      style={{
                        float: 'right',
                      }}
                    >
                      <Tag color={item.run === 1 ? 'green' : item.run === 2 ? 'red' : 'orange'}>
                        {item.run === 1 ? '进行中' : item.run === 2 ? '已结束' : '已暂停'}
                      </Tag>
                      <Tag color={gradeColor}>{gradeName}</Tag>
                      {item.isLinkage === 1 && <Tag color="orange">{linkageTypeName}</Tag>}
                      {item.showView === 1 && item.isView === 0 ? (
                        <Tag color="red">未阅读</Tag>
                      ) : item.showSubmit === 1 && item.isSubmit === 0 ? (
                        <Tag color="red">未报送</Tag>
                      ) : (
                        <></>
                      )}
                    </div>
                  </div>
                }
                description={
                  <>
                    <Typography.Paragraph ellipsis={true}>
                      {
                        <span
                          style={{
                            color: '#888A8C',
                            fontSize: 15,
                          }}
                        >
                          {item.name}
                        </span>
                      }
                    </Typography.Paragraph>
                    <div
                      style={{
                        marginTop: 16,
                        marginRight: 18,
                      }}
                    >
                      <span
                        style={{
                          color:
                            item.run === 1
                              ? '#F47983'
                              : item.run === 2
                              ? '#888A8C'
                              : 'orange',
                        }}
                      >
                        截止：
                        {item.deadlineTime.slice(0,11)}
                      </span>
                      <span
                        style={{
                          float: 'right',
                        }}
                      >
                        {moment(item.createdTime).fromNow()}
                      </span>
                    </div>
                  </>
                }
              />
            </Card>
          </div>
        }
        initialValues={{}}
        onVisibleChange={(visible: boolean) => {
          if (visible) {
            //加载权限树请求网络
            loadSelectTopicManageTreeAssignOrganization();
            loadSelectTopicManageTreeLinkageOrganization();
            loadCuesTopicDetails();
          } else {
            onRefurbish();
          }
        }}
        onValuesChange={(values) => {
          if (values.assignOrganizationIds !== undefined) {
            formRef.current?.setFieldsValue({
              assignOrganizationIds: dataTopicDetails?.cascaderAssignOrganizations,
            });
          }
          if (values.linkageOrganizationIds !== undefined) {
            formRef.current?.setFieldsValue({
              linkageOrganizationIds: dataTopicDetails?.cascaderLinkageOrganizations,
            });
          }
          if (values.deadlineTime !== undefined) {
            formRef.current?.setFieldsValue({
              deadlineTime: [dataTopicDetails?.createdTime, dataTopicDetails?.deadlineTime],
            });
          }
        }}
        submitter={false}
        onFinish={async (values) => {}}
      >
        <Descriptions size="small">
          <Descriptions.Item label="单位">
            {dataTopicDetails?.createdOrganizationName}
          </Descriptions.Item>
          <Descriptions.Item label="创建人">
            {dataTopicDetails?.createdAccountName}
          </Descriptions.Item>
          <Descriptions.Item label="联系方式">
            {dataTopicDetails?.createdAccountPhone}
          </Descriptions.Item>
        </Descriptions>
        <Descriptions
          size="small"
          style={{
            marginTop: 24,
          }}
        >
          <Descriptions.Item label="创建日期">
            <Typography.Text type="success">{dataTopicDetails?.createdTime}</Typography.Text>
          </Descriptions.Item>
          <Descriptions.Item label="截止日期">
            <Typography.Text type="danger">{dataTopicDetails?.deadlineTime}</Typography.Text>
          </Descriptions.Item>
        </Descriptions>
        <div
          style={{
            marginTop: 24,
          }}
        >
          {/* <ProFormCascader
            width="xl"
            label={
              <span
                style={{
                  color: 'rgba(0, 0, 0, 0.45)',
                }}
              >
                指派征集单位：
              </span>
            }
            name="assignOrganizationIds"
            placeholder="选择单位"
            fieldProps={{
              options: treeAssignOrganizationData,
              showSearch: { filter },
              multiple: true,
              removeIcon: false,
              allowClear: false,
              maxTagCount: 'responsive',
              showCheckedStrategy: Cascader.SHOW_CHILD,
            }}
          /> */}
        </div>
        <div
          style={{
            marginTop: 24,
          }}
        >
          <span
            style={{
              color: 'rgba(0, 0, 0, 0.45)',
            }}
          >
            选题内容：
          </span>
          <Typography.Paragraph
            style={{
              marginTop: 8,
            }}
          >
            <blockquote>{dataTopicDetails?.content}</blockquote>
          </Typography.Paragraph>
        </div>
        <Divider />
        {/* {dataTopicDetails?.isLinkage === 1 && dataTopicDetails?.cascaderLinkageOrganizations && (
          <ProFormCascader
            width="xl"
            label={
              <span
                style={{
                  color: 'rgba(0, 0, 0, 0.45)',
                }}
              >
                {dataTopicDetails?.linkageType === 1
                  ? '协助媒体'
                  : dataTopicDetails?.linkageType === 2
                  ? '联动部门'
                  : dataTopicDetails?.linkageType === 3
                  ? '协助媒体、单位'
                  : '协助媒体、单位'}
              </span>
            }
            name="linkageOrganizationIds"
            placeholder="选择单位"
            fieldProps={{
              options: treeLinkageOrganizationData,
              showSearch: { filter },
              multiple: true,
              removeIcon: false,
              allowClear: false,
              maxTagCount: 'responsive',
              showCheckedStrategy: Cascader.SHOW_CHILD,
            }}
          />
        )} */}
        {dataTopicDetails?.linkageDescribes && (
          <div
            style={{
              marginTop: 8,
            }}
          >
            {dataTopicDetails?.linkageType === 1
              ? '协助媒体描述'
              : dataTopicDetails?.linkageType === 2
              ? '联动部门描述'
              : dataTopicDetails?.linkageType === 3
              ? '协助媒体、单位描述'
              : '协助媒体、单位描述'}
            ：
            <Typography.Paragraph>
              <blockquote>{dataTopicDetails?.linkageDescribes}</blockquote>
            </Typography.Paragraph>
          </div>
        )}
        <TableSubmit
          mode={4}
          item={item}
          onRefurbish={function (): void {
            onRefurbish();
          }}
        />
      </DrawerForm>
    );
  };

  return drawerFormView();
};
export default TableTopicAssistDetails;
